using System;
using System.Collections.Generic;
using System.Data;
using Smarly.Bussines;
using Smarly.Core;

namespace Confcloud.Core.Architecture
{
	public abstract class RestObject: ModelStateObject
	{
		public static List<TObj> ListMapping<TObj>(IDataReader reader, Func<IDataReader, TObj> readRow)
		{
			List<TObj> result = new List<TObj>();
			while (reader.Read())
			{
				result.Add(readRow.Invoke(reader));
			}
			return result;
		}
	}
/*
	public interface IModelState
	{
		ModelStateDictionary ModelState { get; set; }
		void Validate(RestType restType, string language);
	}*/

	public abstract class RestObject<T> : RestObject//, IModelState
	{
		public abstract T Get();
		public abstract T Post();
		public abstract T Put();
		public abstract T Delete();

/*		public ModelStateDictionary _modelState = null;
		public ModelStateDictionary ModelState
		{
			get
			{
				if (_modelState == null)
					throw new ApplicationException("Get null ModelState");
				return _modelState;
			}
			set
			{
				if (value == null)
					throw new ApplicationException("Set null ModelState");
				_modelState = value;
			}
		}

		public virtual void Validate(RestType restType, string language)
		{
			ModelMetadata metadata = new EmptyModelMetadataProvider().GetMetadataForType(() => this, typeof(T));
			ControllerContext controllerContext = new ControllerContext();

			ModelValidator validator = ConfcloudModelValidator.GetModelValidator(metadata, controllerContext, restType, language);

			IEnumerable<ModelValidationResult> results = validator.Validate(this);
			foreach (var v in results)
			{
				ModelState.AddModelError(v.MemberName, v.Message);
			}
		}

		protected virtual string UserLanguage { get { throw new NotImplementedException(); } }
		protected virtual string Version { get { return "2"; } }

		protected void OnSqlInfoMessage(object sender, SqlInfoMessageEventArgs args)
		{
			foreach (var pi in GetType().GetProperties())
			{
				var messageKey = args.Message;
				string propertyName = pi.Name;
				if (pi.GetCustomAttributes(typeof(DatabaseValidationAttribute), true).Cast<DatabaseValidationAttribute>().Any(attr => attr.Key == messageKey))
				{
					AddError(propertyName, messageKey);
				}
			}
		}

		protected void AddError(string propertyName, string messageKey)
		{
			HtmlString htmlString = AspectHelper.Value("Validator.Validation." + messageKey, UserLanguage) ?? new HtmlString(messageKey);
			ModelState.AddModelError(propertyName, htmlString.ToString());
		}*/
	}
}